#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Plugin demo escrito por Diego Hahn - 2010

import gtk

import mmap
import struct
import os

import pluginmanager
import compression

__version__ = "0.8"
__author__ = "Diego Hansen Hahn"

@pluginmanager.register('DEFLATE-SCAN')
def deflate_scan(*args, **kwargs):
    fd = kwargs['infile']
    min_size = kwargs['min_size']
    max_size = kwargs['max_size']

    resultsHuff = []
    resultsHuffLZ = []

    address = 0

    # Passo 1 - Encontrar dados comprimidos com Huffman 8 Bits
    while True:
        try:
            header = struct.unpack('<L', fd[address:address+4])[0]
            size = header >> 8
            flag = header & 0xFF
            if flag in (0x24, 0x28) and (size > min_size and size < max_size):
                if compression.huffman.try_uncompress(fd, address, size):

                    while gtk.events_pending():
                        gtk.main_iteration()

                    resultsHuff.append(address)
            address += 4
        except:
            break

    # Passo 2 - Descomprimir os dados em Huffman e testar a compressão LZSS
    for i in resultsHuff:
        buffer = compression.huffman.uncompress(fd, i)
        map = mmap.mmap(-1, len(buffer))
        map.write(buffer.tostring())
        map.seek(0,0)

        header = struct.unpack('<L', map[0:4])[0]
        flag = header & 0xFF
        size = header >> 8
        if flag == 0x10:
            ret = compression.lzss.try_uncompress(map, 0, size)
            if ret:

                while gtk.events_pending():
                    gtk.main_iteration()
                resultsHuffLZ.append((i, 'DEFLATE'))

        map.close()

    return resultsHuffLZ

@pluginmanager.register('DEFLATE-UNCOMPRESS')
def deflate_decoder(*args, **kwargs):
    address = kwargs['address']
    fd = kwargs['infile']

    buffer = compression.huffman.uncompress(fd, address)
    map = mmap.mmap(-1, len(buffer))
    map.write(buffer.tostring())

    buffer = compression.lzss.uncompress(map, 0)
    map.close()

    return buffer

@pluginmanager.register('DEFLATE-COMPRESS')
def deflate_encoder(*args, **kwargs):
    flag = showDialog()

    fd = kwargs['infile']
    buffer = compression.lzss.compress(fd)
    map = mmap.mmap(-1, len(buffer))
    map.write(buffer.tostring())
    map.seek(0,0)

    buffer = compression.huffman.compress(map, flag)
    map.close()
    return buffer

def showDialog():

    dlg = gtk.Dialog(title = u"Huffman - Bitdepth",
                     parent = None,
                     flags = gtk.DIALOG_MODAL,
                     buttons = None)

    dlg.set_position(gtk.WIN_POS_CENTER_ALWAYS)

    dlg.add_button("4 Bits", 4)
    dlg.add_button("8 Bits", 8)

    while True:
        ret = dlg.run()
        if ret in (4, 8):
            dlg.destroy()
            break
    return ret
